﻿import 'package:azring/core/controllers/ring_controller.dart';
import 'package:azring/services/ring_service.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'exercise_record_state.dart';
import '../routes.dart';

/// 运动记录控制器
class ExerciseRecordLogic extends GetxController {
  final ExerciseRecordState state = ExerciseRecordState();

  // 获取戒指控制器
  RingController get ringController => Get.find<RingController>();

  // 获取戒指服务
  RingService get ringService => Get.find<RingService>();

  @override
  void onInit() {
    super.onInit();
    startTrainingStateMonitoring();
    // 延迟加载历史训练记录，避免在构建阶段调用Toast
    Future.delayed(const Duration(milliseconds: 100), () {
      queryHistoryTrainingRecords();
    });
  }

  @override
  void onClose() {
    state.stopTrainingStateMonitoring();
    super.onClose();
  }

  /// 加载运动记录
  void loadExerciseRecords() {
    state.refreshRecords();
  }

  /// 刷新运动记录
  void refreshExerciseRecords() {
    loadExerciseRecords();
  }

  /// 查看运动记录详情
  void viewExerciseRecordDetail(ExerciseRecord record) {
    // TODO: 跳转到运动记录详情页面
    Toast.show('查看 ${record.exerciseName} 的详细记录');
  }

  /// 开始训练状态监控
  void startTrainingStateMonitoring() {
    state.startTrainingStateMonitoring();

    // 模拟训练状态变化（实际应用中应该监听设备状态）
    Future.delayed(const Duration(seconds: 5), () {
      state.updateTrainingState(TrainingState.preparing);
    });

    Future.delayed(const Duration(seconds: 10), () {
      state.updateTrainingState(TrainingState.running);
    });
  }

  /// 查询支持的训练类型
  void querySupportedTrainingTypes() {
    state.querySupportedTrainingTypes();
  }

  /// 查询历史训练记录
  void queryHistoryTrainingRecords() async {
    state.queryHistoryTrainingRecords();

    try {
      // 从设备加载历史训练数据
      loadDeviceHistoryTraining();
      // 暂时注释API调用
      // await loadExerciseList();
    } catch (e) {
      print('❌ 查询历史训练记录失败: $e');
      // 不显示Toast，避免在构建阶段触发UI更新
    }
  }

  /// 从设备加载历史训练数据
  void loadDeviceHistoryTraining() {
    try {
      // 监听设备历史训练数据
      ever(ringService.historyTrainingListRx, (trainingList) {
        print('📊 收到设备历史训练数据: ${trainingList.length} 条');
        
        // 转换为HistoryTrainingRecord
        final records = <HistoryTrainingRecord>[];
        for (final item in trainingList) {
          try {
            final record = _parseDeviceTrainingItem(item);
            if (record != null) {
              records.add(record);
            }
          } catch (e) {
            print('❌ 解析设备训练记录失败: $e');
          }
        }
        
        // 更新状态
        state.historyTrainingRecords.value = records;
        print('✅ 成功加载 ${records.length} 条有效训练记录');
      });
      
      // 如果已经有数据，立即处理
      if (ringService.historyTrainingListRx.isNotEmpty) {
        final trainingList = ringService.historyTrainingListRx;
        final records = <HistoryTrainingRecord>[];
        for (final item in trainingList) {
          try {
            final record = _parseDeviceTrainingItem(item);
            if (record != null) {
              records.add(record);
            }
          } catch (e) {
            print('❌ 解析设备训练记录失败: $e');
          }
        }
        state.historyTrainingRecords.value = records;
        print('✅ 成功加载 ${records.length} 条有效训练记录');
      }
    } catch (e) {
      print('❌ 加载设备历史训练数据失败: $e');
    }
  }

  /// 解析设备训练记录项
  HistoryTrainingRecord? _parseDeviceTrainingItem(Map<String, dynamic> item) {
    try {
      // 从rawData字符串中提取信息
      final rawData = item['rawData'] as String? ?? '';
      
      // 解析格式: CRPHistoryTrainingInfo{startTime=1755332255000, rawTime=1755332255000, type=104}
      final startTimeMatch = RegExp(r'startTime=(\d+)').firstMatch(rawData);
      final rawTimeMatch = RegExp(r'rawTime=(\d+)').firstMatch(rawData);
      final typeMatch = RegExp(r'type=(\d+)').firstMatch(rawData);
      
      if (startTimeMatch == null || rawTimeMatch == null || typeMatch == null) {
        print('❌ 无法解析训练记录: $rawData');
        return null;
      }
      
      final startTimeMs = int.parse(startTimeMatch.group(1)!);
      final rawTimeMs = int.parse(rawTimeMatch.group(1)!);
      final type = int.parse(typeMatch.group(1)!);
      
      final startTime = DateTime.fromMillisecondsSinceEpoch(startTimeMs);
      
      // 获取训练类型名称
      final trainingName = _getTrainingTypeName(type);
      
      return HistoryTrainingRecord(
        trainingId: rawTimeMs,
        trainingType: type,
        trainingName: trainingName,
        startTime: startTime,
        endTime: startTime, // 设备数据没有结束时间，暂时使用开始时间
        duration: 0, // 设备数据没有持续时间
        calories: 0, // 设备数据没有卡路里
        state: TrainingState.completed,
        averageHeartRate: null,
        rawTime: rawTimeMs,
      );
    } catch (e) {
      print('❌ 解析设备训练记录项失败: $e');
      return null;
    }
  }

  /// 从API加载锻炼列表（暂时注释）
  Future<void> loadExerciseList() async {
    try {
      state.isQueryingHistory.value = true;

      // 获取设备序列号
      final deviceSn = ringController.getCurrentDeviceSn();
      if (deviceSn.isEmpty) {
        print('❌ 设备未连接，无法加载锻炼列表');
        // 不显示Toast，避免在构建阶段触发UI更新
        return;
      }

      // 获取当前日期
      final now = DateTime.now();
      final recordDate =
          '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';

      print('📊 开始加载锻炼列表: deviceSn=$deviceSn, recordDate=$recordDate');

      // 调用API获取锻炼列表
      final exerciseList = await ringService.queryExerciseList(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: '1',
      );

      print('✅ 获取到 ${exerciseList.length} 条锻炼记录');

      // 转换为HistoryTrainingRecord
      final records = <HistoryTrainingRecord>[];
      for (final item in exerciseList) {
        try {
          final record = _parseExerciseItem(item);
          if (record != null) {
            records.add(record);
          }
        } catch (e) {
          print('❌ 解析锻炼记录失败: $e');
        }
      }

      // 更新状态
      state.historyTrainingRecords.value = records;
      print('✅ 成功加载 ${records.length} 条有效锻炼记录');
    } catch (e) {
      print('❌ 加载锻炼列表失败: $e');
      // 不显示Toast，避免在构建阶段触发UI更新
    } finally {
      state.isQueryingHistory.value = false;
    }
  }

  /// 解析锻炼记录项
  HistoryTrainingRecord? _parseExerciseItem(Map<String, dynamic> item) {
    try {
      final id = item['id']?.toString() ?? '';
      final type = item['exerciseType'] as int? ?? 0;
      final startDateStr = item['startDate'] as String? ?? '';
      final endDateStr = item['endDate'] as String? ?? '';
      final duration = item['exerciseTime'] as int? ?? 0;
      final calories = item['exerciseCalorie'] as int? ?? 0;

      // 解析时间
      DateTime startTime;
      DateTime endTime;

      try {
        startTime = DateTime.parse(startDateStr);
        endTime = DateTime.parse(endDateStr);
      } catch (e) {
        print('❌ 时间解析失败: $e');
        return null;
      }

      // 获取训练类型名称
      final trainingName = _getTrainingTypeName(type);

      return HistoryTrainingRecord(
        trainingId: int.tryParse(id) ?? 0,
        trainingType: type,
        trainingName: trainingName,
        startTime: startTime,
        endTime: endTime,
        duration: duration,
        calories: calories,
        state: TrainingState.completed,
        averageHeartRate: item['averageHeartRate'] as int?,
        rawTime: startTime.millisecondsSinceEpoch,
      );
    } catch (e) {
      print('❌ 解析锻炼记录项失败: $e');
      return null;
    }
  }

  /// 获取训练类型名称
  String _getTrainingTypeName(int type) {
    switch (type) {
      case 0:
        return '自由训练';
      case 1:
        return '跑步';
      case 2:
        return '散步';
      case 3:
        return '骑行';
      case 4:
        return '游泳';
      case 5:
        return '力量训练';
      case 6:
        return '瑜伽';
      case 7:
        return '举重';
      case 8:
        return '舞蹈';
      case 23:
        return '其他运动';
      default:
        return '未知运动';
    }
  }

  /// 处理设备历史训练记录回调
  void onDeviceHistoryTrainingChange(List<Map<String, dynamic>> historyData) {
    print('📱 收到设备历史训练记录回调: ${historyData.length} 条');
    state.updateRealHistoryTrainingRecords(historyData);
  }

  /// 查询动作详情
  void queryActionDetails(int trainingId) {
    state.queryActionDetails(trainingId);
  }

  /// 查看历史训练记录详情
  void viewHistoryTrainingDetail(HistoryTrainingRecord record) {
    // 跳转到运动记录详情页面
    Get.toNamed(ExerciseRoutes.exerciseRecordDetail, arguments: record);
  }
}
